import { connect, history } from 'umi';
import { Drawer, Table, Tooltip, message } from 'antd';
import React, { useEffect, useMemo, useRef } from 'react';
import { Descriptions, useDescriptions } from '@/components/Descriptions';

import { useSourceManage } from '../common/useSourceManage';
import { SourceManageAPI } from '../common/type';
import { fetchFailureBidServices } from '../services/UpdateService';

import { SchemaManage } from '@/components/SchemaComponent';
import { TipsErrorModalNew } from '@/components/TipsErrorModalNew';
import { UpdataApplyModal } from './UpdataApplyModal';
import { getColorTextLoadMap, getInvoiceCode, getKeyRouter } from '@/utils';
import { DictionaryService } from '../../ApplyManage/services/DictionaryService';
import { setTableRowClassName } from '../common/Format';
import { handleOneObjectData } from '../../ApplyManage/common/Format';
import { getPackTableColumns } from '../../ApplyManage/mconfig';
import { EyeOutlined } from '@ant-design/icons';
import { renderFileFunc } from '../../Acommon';
import ScrollBarLayout from '@/components/ScrollBarLayout';

const SourceManageView: React.FC<SourceManageAPI.IManageType> = ({ curRes, locationProps }) => {
  /**
   * 采购实施管理页hooks
   * */
  const {
    tableProps,
    searchProps,
    actionList,
    isShowAnnoun,
    setIsShowAnnoun,
    requestManage,
    isShowModal,
    setIsShowModal,
    isShowDrawer,
    setIsShowDrawer,
  } = useSourceManage(curRes, locationProps);

  const { fetchFailureBidRun, fetchFailureBidLoading } = fetchFailureBidServices((res) => {
    if (res?.msgFlag) {
      message?.success(res?.msg);
      requestManage({});
    }
  });

  const { supplyWayList } = DictionaryService(); /**采购办法*/

  /** 表格表单配置 */
  const [configs, methods] = useDescriptions({
    labelWidth: 210,
    schemas: [
      {
        label: '一、标包信息',
        field: 'Title',
        component: 'Title',
      },
      {
        label: '标包名称',
        field: 'packName',
        component: 'Render',
        slotRender: (text: string) => {
          return <span style={{ marginLeft: '8px' }}>{text || '--'}</span>;
        },
      },
      {
        label: '包号',
        field: 'packCode',
        component: 'Input',
        placeholder: '自动带出',
        disabled: true,
      },
      {
        label: '采购类别',
        field: 'supplyTypeName',
        component: 'Render',
        slotRender: (text: string) => {
          const { colorText, color } = getColorTextLoadMap(text);
          if (colorText) {
            return <div style={{ color, paddingLeft: '8px' }}>{colorText || '--'}</div>;
          } else {
            return <div style={{ color: '#c4c4c3', paddingLeft: '8px' }}>自动带出</div>;
          }
        },
      },
      {
        label: '预算金额',
        field: 'expectSum',
        placeholder: '自动带出',
        component: 'Input',
        disabled: true,
        contentAfter: '元',
      },

      {
        label: '采购组织类型',
        field: 'procureOrgName',
        component: 'Render',
        placeholder: '自动带出',
        disabled: false,
        slotRender: (text: string) => {
          const { colorText, color } = getColorTextLoadMap(text);
          if (colorText) {
            return <div style={{ color, paddingLeft: '8px' }}>{colorText || '--'}</div>;
          } else {
            return <div style={{ color: '#c4c4c3', paddingLeft: '8px' }}>自动带出</div>;
          }
        },
      },
      {
        label: '拟定采购方式',
        placeholder: '自动带出',
        field: 'procureRealName',
        component: 'Render',
        slotRender: (text: string) => {
          const { colorText, color } = getColorTextLoadMap(text);
          if (colorText) {
            return <div style={{ color, paddingLeft: '8px' }}>{colorText || '--'}</div>;
          } else {
            return <div style={{ color: '#c4c4c3', paddingLeft: '8px' }}>自动带出</div>;
          }
        },
      },
      {
        label: '标的来源',
        field: 'supplyWay',
        placeholder: '自动带出',
        component: 'Select',
        colSpan: 1,
        options: supplyWayList,
        disabled: true,
        fieldNames: {
          label: 'name',
          value: 'value',
        },
      },
      {
        label: '采购方式变更申请单',
        field: 'changeID',
        component: 'Render',
        slotRender: (text) => {
          return (
            <div style={{ paddingLeft: '8px' }}>
              {text ? (
                <Tooltip title={'查看采购方式变更申请单'}>
                  <a>
                    <EyeOutlined
                      onClick={() => {
                        if (curRes?.['/purchaseSourceChangeController/getSourceChangeById/{id}/{currentUserID}']) {
                          history.push({
                            pathname: `/purchaseSourceChangeController/getSourceChangeById/{id}/{currentUserID}/:${getKeyRouter()}${getKeyRouter()}`,
                            state: {
                              info: { changeID: text },
                              type: 'view',
                            },
                          });
                        } else {
                          message?.error('抱歉，暂无查看权限！');
                        }
                      }}
                    />
                  </a>
                </Tooltip>
              ) : (
                <span>--</span>
              )}
            </div>
          );
        },
      },
      {
        label: '技术规范',
        field: 'skillNormURL',
        placeholder: '请上传技术规范',
        component: 'Render',
        colSpan: isShowDrawer?.resObj?.supplyWay && isShowDrawer?.resObj?.supplyWay == 1 ? 1 : 0,
        slotRender: (text, record) => {
          return (
            <span style={{ marginLeft: 8 }}>
              {renderFileFunc({
                record: isShowDrawer?.resObj || {},
                fileName: 'skillNormURL',
                downloadAddress: '/purchaseApplyController/downloadFile',
                returnStr: '/',
              })}
            </span>
          );
        },
      },
      {
        label: '调研报告',
        field: 'researchReportURL',
        placeholder: '请上传调研报告',
        component: 'Render',
        colSpan: isShowDrawer?.resObj?.supplyWay && isShowDrawer?.resObj?.supplyWay == 1 ? 1 : 0,
        slotRender: (text, record) => {
          return (
            <span style={{ marginLeft: 8 }}>
              {renderFileFunc({
                record: isShowDrawer?.resObj || {},
                fileName: 'researchReportURL',
                downloadAddress: '/purchaseApplyController/downloadFile',
                returnStr: '/',
              })}
            </span>
          );
        },
      },
      {
        label: '是否进口',
        field: 'importFlag',
        component: 'Render',
        colSpan: isShowDrawer?.resObj?.supplyWay && isShowDrawer?.resObj?.supplyWay == 1 ? (!isShowDrawer?.resObj?.importFlag ? 2 : 1) : 0,
        slotRender: (text: any = 0) => {
          return <span style={{ marginLeft: 8 }}>{text == 0 ? '否' : '是'}</span>;
        },
      },
      {
        label: '进口专业人员论证意见',
        field: 'needImportURL',
        placeholder: '请上传进口专业人员论证意见',
        component: 'Render',
        colSpan: isShowDrawer?.resObj?.supplyWay && isShowDrawer?.resObj?.supplyWay == 1 && isShowDrawer?.resObj?.importFlag == 1 ? 1 : 0,
        ishidden: isShowDrawer?.resObj?.supplyWay && isShowDrawer?.resObj?.supplyWay == 1 && isShowDrawer?.resObj?.importFlag == 1 ? false : true,
        slotRender: (text, record) => {
          return (
            <span style={{ marginLeft: 8 }}>
              {renderFileFunc({
                record: isShowDrawer?.resObj || {},
                fileName: 'needImportURL',
                downloadAddress: '/purchaseApplyController/downloadFile',
                returnStr: '/',
              })}
            </span>
          );
        },
      },
      {
        label: '是否单一来源',
        field: 'singleFlag',
        component: 'Render',
        colSpan: isShowDrawer?.resObj?.supplyWay && isShowDrawer?.resObj?.supplyWay == 1 ? (!isShowDrawer?.resObj.singleFlag ? 2 : 1) : 0,
        slotRender: (text: any = 0) => {
          return <span style={{ marginLeft: 8 }}>{text == 0 ? '否' : '是'}</span>;
        },
      },
      {
        label: '单一来源论证意见',
        field: 'needSingleURL',
        placeholder: '请上传单一来源论证意见',
        component: 'Render',
        colSpan: isShowDrawer?.resObj?.supplyWay && isShowDrawer?.resObj?.supplyWay == 1 && isShowDrawer?.resObj?.singleFlag == 1 ? 1 : 0,
        ishidden: isShowDrawer?.resObj?.supplyWay && isShowDrawer?.resObj?.supplyWay == 1 && isShowDrawer?.resObj?.singleFlag == 1 ? false : true,
        slotRender: (text, record) => {
          return (
            <span style={{ marginLeft: 8 }}>
              {renderFileFunc({
                record: isShowDrawer?.resObj || {},
                fileName: 'needSingleURL',
                downloadAddress: '/purchaseApplyController/downloadFile',
                returnStr: '/',
              })}
            </span>
          );
        },
      },
      {
        label: '需求论证意见',
        field: 'needProofURL',
        placeholder: '请上传需求论证意见',
        component: 'Render',
        colSpan:
          isShowDrawer?.resObj?.supplyWay == 1 && isShowDrawer?.resObj?.expectSum && Number(isShowDrawer?.resObj?.expectSum) >= 500000
            ? Number(isShowDrawer?.resObj?.expectSum) >= 1000000
              ? 1
              : 2
            : 0,
        slotRender: (text, record) => {
          return (
            <span style={{ marginLeft: 8 }}>
              {renderFileFunc({
                record: isShowDrawer?.resObj || {},
                fileName: 'needProofURL',
                downloadAddress: '/purchaseApplyController/downloadFile',
                returnStr: '/',
              })}
            </span>
          );
        },
      },
      {
        label: '是否通过主任办公室会议',
        field: 'directorMeetingFlag',
        placeholder: '请上传是否通过主任办公室会议',
        component: 'Render',
        colSpan: isShowDrawer?.resObj?.supplyWay == 1 && isShowDrawer?.resObj?.expectSum && Number(isShowDrawer?.resObj?.expectSum) >= 1000000 ? 1 : 0,
        slotRender: (text: any = 0) => {
          return <span style={{ marginLeft: 8 }}>{text == 0 ? '否' : '是'}</span>;
        },
      },
    ],
  });

  const dataMemo = useMemo(() => {
    if (isShowDrawer?.isShow && isShowDrawer?.resObj?.mpurchaseSourceMaterials) {
      methods?.setFieldsValue(isShowDrawer?.resObj);
      let data = handleOneObjectData(isShowDrawer?.resObj?.mpurchaseSourceMaterials);
      return data?.map((i) => {
        return { ...i, needParams: i?.specInfo };
      });
    } else {
      return [];
    }
  }, [isShowDrawer]);

  /** 进入页面主动更新 */
  useEffect(() => {
    requestManage({});
  }, [history.location.pathname]);

  return (
    <div
      style={{
        position: 'relative',
        overflow: 'hidden',
        height: '100%',
        width: '100%',
      }}
    >
      <SchemaManage ref={useRef()} searchProps={searchProps} actionList={actionList} tableProps={tableProps} />

      <Drawer
        title="标包信息"
        placement="right"
        closable={false}
        onClose={() => setIsShowDrawer({})}
        open={isShowDrawer?.isShow}
        getContainer={false}
        style={{ position: 'absolute' }}
        width={document.body?.clientWidth * 0.5}
        bodyStyle={{
          padding: 0,
          overflow: 'hidden',
          display: 'flex',
          flexDirection: 'column',
        }}
        className={'packInfoDrawer'}
      >
        <ScrollBarLayout style={{ padding: '10px' }}>
          <Descriptions config={configs} />
          <div className={'apply-update-title-divClassName'}>二、标包物料</div>
          <div className={`list-table`} style={{ height: '100%', overflow: 'hidden' }}>
            <Table
              bordered
              size="small"
              rowKey={'materialID'}
              pagination={false}
              rowClassName={setTableRowClassName}
              scroll={{ x: 1000, y: 1000 }}
              dataSource={dataMemo}
              rowSelection={undefined}
              columns={getPackTableColumns({
                applyInfo: null,
                finallyType: 'view',
                changeTargetInfo: () => {},
                onRemove: () => {},
              })}
            />
          </div>
        </ScrollBarLayout>
      </Drawer>

      {isShowAnnoun?.isShow && (
        <TipsErrorModalNew
          onClose={() => {
            setIsShowAnnoun({ isShow: false, resObj: {} });
          }}
          modalOnOK={() => {
            let id = isShowAnnoun?.resObj?.id;
            if (id) fetchFailureBidRun({ id, sourceCode: getInvoiceCode('SS') });
          }}
          modalTip={<>请确认是否重新发布招标公告！</>}
          modalLoading={fetchFailureBidLoading}
        />
      )}
      {/* 是否显示申请标题弹框 */}
      {isShowModal?.isShow && <UpdataApplyModal onClose={() => setIsShowModal({ isShow: false, resObj: {} })} curRes={curRes} locationProps={locationProps} />}
    </div>
  );
};

export default connect(({ baseLogin }: Record<string, any>) => ({
  curRes: baseLogin?.permissions,
}))(SourceManageView);
